package com.akk.platform.oem.business;

import com.akk.module.avs.entity.AvsYbCardRaider;
import com.akk.module.avs.model.request.AvsYbCardRaiderRequest;
import com.akk.module.avs.service.AvsYbCardRaiderService;
import com.akk.module.upload.service.PictureService;
import com.akk.utils.PageUtils;
import com.akk.utils.Query;
import com.akk.utils.RestResponse;
import com.akk.utils.ShiroUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;

import java.util.List;
import java.util.Map;

@Component
public class YbCardRaiderBusiness {

    @Autowired
    private AvsYbCardRaiderService avsYbCardRaiderService;

    @Autowired
    private PictureService pictureService;

    public RestResponse list(Query query, BindingResult bindingResult){
        if (bindingResult.hasErrors())
            return RestResponse.build("1",bindingResult.getFieldError().getDefaultMessage(),"");
        PageHelper.startPage(query.getPage(),query.getLimit());
        Map params = query.getSearch();
        params.put("appId", ShiroUtils.getAdmin().getAppId());
        List<AvsYbCardRaider> list = avsYbCardRaiderService.findByParams(params);
        return RestResponse.build(PageUtils.buildPage(list,(int) new PageInfo<>(list).getTotal(),query));
    }

    public RestResponse save(AvsYbCardRaiderRequest request,BindingResult bindingResult){
        if (bindingResult.hasErrors())
            return RestResponse.build("1",bindingResult.getFieldError().getDefaultMessage(),"");
        if (request.getIcon() == null)
            return RestResponse.build("1","请上传图片","");
        Map result = pictureService.uploadPicture(request.getIcon());
        if (result.get("status").toString().equals("1"))
            return RestResponse.build("1","文件上传失败","");
        request.setImage(result.get("url").toString());
        request.setAppId(ShiroUtils.getAdmin().getAppId());
        avsYbCardRaiderService.save(request);
        return RestResponse.build("success");
    }

    public RestResponse del(Long raiderId){
        AvsYbCardRaider raider = avsYbCardRaiderService.findById(raiderId);
        if (raider == null)
            return RestResponse.build("1","信息不存在","");
        if (!StringUtils.isEmpty(raider.getImage()) && raider.getImage().length() > 8)
            pictureService.removeFile(raider.getImage());
        avsYbCardRaiderService.del(raiderId);
        return RestResponse.build("success");
    }


}
